﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ExcelToSql
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Gets WPF ConnectionManager interface.
        /// </summary>
        public ConnectionManagerBinding ConnectionManager
        {
            get
            {
                return (ConnectionManagerBinding)FindResource("MyConnectionManagerBinding");
            }
        }

        /// <summary>
        /// Initialize window.
        /// </summary>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ConnectionManager.ConnectionKey = "Default";
            ConnectionManager.TextBoxLog = textBoxLog;
            ConnectionManager.Prefix = "";
            ConnectionManager.Folder = new Uri(new Uri(typeof(MainWindow).Assembly.CodeBase), ".").LocalPath;
        }

        private void buttonRun_Click(object sender, RoutedEventArgs e)
        {
            new Task(new Action(
                () =>
                {
                    try
                    {
                        Script.Run();
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            )).Start();
        }

        private void buttonDrop_Click(object sender, RoutedEventArgs e)
        {
            ConnectionManager.OnLog("Begin");
            ConnectionManager.OnLog("SqlDrop");
            Script.SqlDrop();
            ConnectionManager.OnLog("End");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ConnectionManager.Folder = dialog.SelectedPath;
            }
        }
    }

    /// <summary>
    /// ConnectionManager interface to WPF. See also App.xaml where it
    /// is defined as static resorce.
    /// </summary>
    public class ConnectionManagerBinding : INotifyPropertyChanged
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        public ConnectionManagerBinding()
        {
            ConnectionManager.Log += Log;
        }

        /// <summary>
        /// TextBox to which logs should be written.
        /// </summary>
        public TextBox TextBoxLog;

        /// <summary>
        /// Log comming from ConnectionManager.
        /// </summary>
        private void Log(string text)
        {
            if (TextBoxLog != null)
            {
                TextBoxLog.Dispatcher.Invoke(new Action(() =>
                {
                    TextBoxLog.Text += DateTime.Now.ToString("HH:mm:ss") + " " + text + "\r\n";
                    TextBoxLog.Focus();
                    TextBoxLog.CaretIndex = TextBoxLog.Text.Length;
                }), null);
            }
        }

        public void OnLog(string text)
        {
            ConnectionManager.OnLog(text);
        }

        private void LogThis()
        {
            if (TextBoxLog != null)
            {
                TextBoxLog.Clear();
                ConnectionManager.LogThis();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string ConnectionKey
        {
            get
            {
                return ConnectionManager.ConnectionKey;
            }
            set
            {
                if (ConnectionManager.ConnectionKey != value)
                {
                    ConnectionManager.ConnectionKey = value;
                    OnPropertyChanged("ConnectionKey");
                    OnPropertyChanged("ConnectionStringDefault");
                    OnPropertyChanged("ConnectionStringList");
                    OnPropertyChanged("ConnectionStringListIndex");
                    //
                    LogThis();
                }
            }
        }

        public string ConnectionStringDefault
        {
            get
            {
                return ConnectionManager.ConnectionStringList["Default"];
            }
            set
            {
                Dictionary<string, string> connectionStringList = ConnectionManager.ConnectionStringList;
                connectionStringList["Default"] = value;
                ConnectionManager.ConnectionStringList = connectionStringList;
                //
                OnPropertyChanged("ConnectionStringDefault");
                OnPropertyChanged("ConnectionStringList");
                OnPropertyChanged("ConnectionStringListIndex");
                //
                LogThis();
            }
        }

        public string[] ConnectionStringList
        {
            get
            {
                return ConnectionManager.ConnectionStringList.Keys.ToArray();
            }
        }

        /// <summary>
        /// Returns index of currently selected ConnectionStrng
        /// </summary>
        public int ConnectionStringListIndex
        {
            get
            {
                int result = Array.IndexOf(ConnectionStringList, ConnectionManager.ConnectionKey);
                return result;
            }
            set
            {
                ConnectionKey = ConnectionStringList[value];
            }
        }

        public string Folder
        {
            get
            {
                return ConnectionManager.ExcelLocalFolder;
            }
            set
            {
                ConnectionManager.ExcelLocalFolder = value;
                OnPropertyChanged("Folder");
                //
                LogThis();
            }
        }

        public string Prefix
        {
            get
            {
                return ConnectionManager.Prefix;
            }
            set
            {
                ConnectionManager.PrefixSet(value);
                OnPropertyChanged("Prefix");
                //
                LogThis();
            }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
